package com.jxauaia.contest.config;

import com.jxauaia.contest.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/auth/login", "/auth/register", "/auth/captcha/**").permitAll()
                        .requestMatchers("/admin/**").hasRole("ADMIN")  // 管理员路径
                        .requestMatchers("/api/admin/**").hasRole("ADMIN")  // 带API前缀的管理员路径
                        .requestMatchers("/user-profile/**").authenticated()  // 用户个人信息需要认证
                        .requestMatchers("/api/user-profile/**").authenticated()  // 带API前缀的用户个人信息
                        .requestMatchers("/public/**", "/uploads/**").permitAll()  // 公开资源
                        .requestMatchers("/api/public/**", "/api/uploads/**").permitAll()  // 带API前缀的公开资源
                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()  // Swagger文档
                        .anyRequest().authenticated()
                )
                .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        ;
        return http.build();
    }
}